package io.github.talelin.latticy.controller.v1;


import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.dto.machine.CreateOrUpdateAswDTO;
import io.github.talelin.latticy.model.AswDO;
import io.github.talelin.latticy.model.AswItemDO;
import io.github.talelin.latticy.service.AswService;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
* @author generator@TaleLin
* @since 2021-05-28
*/
@RestController
@RequestMapping("/v1/asw")
public class AswController {

    @Autowired
    private AswService aswService;

    @GetMapping("")
    public List<AswDO> getAsws(){
        List<AswDO> asw = aswService.findAll();
        return asw ;
    }

    @GetMapping(value = "/fingAllAsw")
    public List<Map<String, Object>> fingAllAsw(){
        List<Map<String, Object>> asw = aswService.fingAllAsw();
        SetAswItem(asw);
        return asw ;
    }
    @GetMapping(value = "/findAswByID")
    public List<Map<String, Object>> findAswByID(Integer ID){
        System.out.println("aaaaaaaaaa"+ID);
        List<Map<String, Object>> asw = aswService.findAswByID(ID);
        SetAswItem(asw);
        return asw ;
    }

    private void SetAswItem(List<Map<String, Object>> asw) {
        for (Map map : asw) {
            List<AswItemDO> aswItem = aswService.fingAllAswItemByID((Integer) map.get("id"));
            map.put("aswItem", aswItem);
        }
    }

    @GetMapping(value = "/selectNameBySortID")
    public String selectNameBySortID( Integer sortID){
        return aswService.selectNameBySortID(sortID) ;
    }

    @GetMapping(value = "/fingAllAswItemByID")
    public List<AswItemDO> fingAllAswItemByID(Integer AswItemID){
        return aswService.fingAllAswItemByID(AswItemID) ;
    }


    @GetMapping("/{id}")
    public AswDO getAsw(@PathVariable("id") Integer id){
        AswDO asw = aswService.getAswById(id);
        if(asw == null){
            throw  new NotFoundException(10022);
        }
        return asw;
    }


    @DeleteMapping("/{id}")
    public DeletedVO deleteAswByID(@PathVariable("id") Integer id){
        AswDO asw = aswService.getAswById(id);

        if (asw == null) {
            throw new NotFoundException(10022);
        }
        aswService.deleteById(asw.getId());
        aswService.deleteAswItemByID(id);
        return new DeletedVO(21);
    }

    @PostMapping("")
    public CreatedVO createAsw(@RequestBody @Validated CreateOrUpdateAswDTO validator) {
        aswService.createAsw(validator);
        return new CreatedVO(20);
    }

}
